<?php
namespace app\api\model;
use think\Model;
use think\Session;
use think\Db;
use think\Exception;
class User extends Model
{
    public function login($account,$root){
        error_reporting(0);
        $db = db('user')->where('account',$account)->find();
        if($db){
            if($db['root']==md5($root.$db['randomcode'])){
                Session::set('account',$db['account']);
                Session::set('id',$db['id']);
                Session::set('name',$db['name']);
                session_write_close();
                return 1;
            }
            else{
                return 3;
            }
        }
        else{
            return 2;
        }
    }
    public function registered($account,$root){
        error_reporting(0);
        $code  = new User;
        $having = Db::name('user')->where('account',$account)->find();
        if($having){
            return 2;
        }else{
            $randomcode = $code->randomcode();
            $db = model('user')->insert([
                'name'     => $account,
                'intergral'=> 0,
                'account'  => $account,
                'root'     => md5($root.$randomcode),
                'location' => null,
                'iphone'   => $account,
                'email'    => null,
                'money'    => 0,
                'agencyid'=> 0,
                'randomcode' => $randomcode
            ]);
            if($db){
                return 1;
            }else{
                return 0;
            }
        }
    }
    /**
     * 生成随机码,然后加入到密码中
     */
    public function randomcode(){
        $pattern = '1234567890abcdefghigklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        for($i=0,$key='';$i<20;$i++)
        {
            $key .= $pattern{mt_rand(0,61)};
        }
        return $key;
    }
    //用户页面信息
    public function information($id){
        $db = model('user')
            ->alias('a')
            ->join('userticket','a.id=userticket.userid','left')
            ->join('ticket','userticket.ticketid=ticket.id','left')
            ->group('a.id')
            ->where('a.id',$id)
            ->field('a.photo,name,iphone,a.money,a.intergral,agencyid,count(ticketid) sumticket')
            ->find();
        return $db;
    }


    public function rechangePh($id,$photo)
    {
        if ($photo)
        {
            //删除原图片
            $data = User::get($id)->getdata();
            $path=ROOT_PATH . 'public' . DS . 'static' . DS . 'img_user'. DS .$data['photo'];
            if(file_exists($path)){
                @unlink($path);
                clearstatcache();
            }
            //上传新图片
            if($photo!=null) {
                // 移动到框架应用根目录/public/static/images/ 目录下
                $info = $photo->move(ROOT_PATH . 'public' . DS . 'static/img_user');
            }
            $change = Db::name('user')->update([
                  'id'    => $id,
                  'photo' => $info->getSaveName()
              ]);
              if($change){
                  return 1;
              }else{
                  return 0;
              }
        }else{
            return 2;
        }
    }
    public function rechangeNa($id,$name){
        if(!empty($name)){
            $change = Db::name('user')->update([
                'id' => $id,
                'name' => $name
            ]);
            if($change){
                return 1;
            }else{
                return 0;
            }
        }
        else{
            return 0;
        }
    }

    /**
     * 查询用户的余额和积分
     * @param $userid  用户id
     * @param $type 查询类型
     */
    public function moneyint($userid,$type)
    {
        if($type == 1)
        {
            $data = Db::name('user')->field('money')->where(['id'=>$userid])->select();
        }
        if($type == 0)
        {
            $data = Db::name('user')->field('intergral')->where(['id'=>$userid])->select();
        }

        if(count($data) == 0)
        {
            return 0;
        }
        else
        {
            return $data;
        }
    }
    public function wxlogin($results,$userInfo,$avatarUrl){
        $code = new User;
        $randomcode = $code->randomcode();
       try {
                //开启事务
            Db::startTrans();
            $db = Db::name('user')->insertGetId([
                'name'     => $userInfo,
                'intergral'=> 0,
                'account'  => md5($randomcode),
                'root'     => md5($randomcode),
                'location' => null,
                'iphone'   => null,
                'email'    => null,
                'money'    => 0,
                'agencyid'=> 0,
                'photo'   => $avatarUrl,
                'randomcode' => $randomcode,
                'times'     => date("Y-m-d H:i:s")
            ]);
            $dbb = Db::name('wxuser')->insertGetId([
                'session_key' => $results['session_key'],
                'openid'      => $results['openid'],
                'userid'      => $db
            ]);
            if (!($db !== false && $dbb !== false)) {
                throw new Exception('出现意外');
            }
            Db::commit();
            $db33 = User::get($dbb);
            Session::set('id',$db33['userid']);
            Session::set('session_key',$db33['session_key']);
            session_write_close();
            return 1;
        }
        catch (Exception $e) {
            //如获取到异常信息，对所有表操作，都会回滚至操作前的状态：
            Db::rollback();
            return 0;
        }
    }
    public function wxdllogin($results){
        $db = Db::name('wxuser')->where('openid',$results['openid'])->find();
        Session::set('id',$db['userid']);
        Session::set('session_key',$db['session_key']);
        return 1;
    }
}